<style lang="less">
    @import '../../../styles/common.less';
    @import '../../my-components/data-table/table.less';
</style>

<template>
  <div>
      <Row>
        <Col span="24">
            <Card>
                <p slot="title">
                    <!-- <Icon type="android-more-horizontal"></Icon> -->
                    定时任务列表
                </p>
                <Row>
                    <Col span="16">
                        <Input placeholder="请输入用户名搜搜..." style="width: 150px" />
                        <Input placeholder="请输入姓名搜搜..." style="width: 150px" />
                        <Button type="primary" shape="circle" icon="ios-search"></Button>
                    </Col>
                    <Col span="3" offset="5" v-if="$hasPerms('system:schedule:save')">
                        <span style="margin: 0 10px;">
                           <Button type="primary" icon="plus" @click="handleAdd()">新增定时任务</Button>
                        </span>
                    </Col>
                </Row>
                <br>
                <Row>
                    <div class="edittable-table-height-con">
                        <data-table :is-loading="isLoading" v-model="jobs" :columns-list="jobColumns"
                                    :total-record="total" :current-page="currentPage" :permissions-prefix="permsSign"
                            @deleteOne="handleDel" @resumeOne="handleResume" @editOne="handleEdit" @stopOne="handleStop"
                            @runOne="handleRun">
                        </data-table>
                    </div>
                </Row>
            </Card>
        </Col>
      </Row>

      <Modal
            v-model="addModal"
            :title="modalTitle"
            :closable='false'
            :mask-closable="false">
        <Form ref="addFrom" :model="addFrom" label-position="top" :rules="rules">
            <FormItem label="Bean名称" prop="beanName">
                <Input v-model="addFrom.beanName"></Input>
            </FormItem>
            <FormItem label="方法名" prop="methodName">
                <Input v-model="addFrom.methodName"></Input>
            </FormItem>
            <FormItem label="参数" prop="params">
                <Input v-model="addFrom.params"></Input>
            </FormItem>
            <FormItem label="cron表达式" prop="cron">
                <Input v-model="addFrom.cron"></Input>
            </FormItem>
            <FormItem label="状态" prop="status">
                <Select v-model="addFrom.status" style="width:200px">
                    <Option v-for="item in statusList" :value="item.value" :key="item.value">{{ item.label }}</Option>
                </Select>
            </FormItem>
            <FormItem label="备注" prop="remark">
                <Input v-model="addFrom.remark"></Input>
            </FormItem>
        </Form>
        <div slot="footer">
            <Button type="text" @click="cancelModal">取消</Button>
            <Button type="primary" :loading="saveLoading" @click="addModalOk">保存</Button>
        </div>
      </Modal>
  </div>

</template>

<script>
import dataTable from '../../my-components/data-table/dataTable.vue';
import jobCol from './job_col.js';

export default {
    name: 'job-index',
    components: {
        dataTable
    },
    data () {
        return {
            isLoading: true,
            saveLoading: false,
            modalTitle:'',
            // 表头
            jobColumns: [],
            // 数据
            jobs: [],
            total: 0,
            currentPage: 1,
            permsSign: 'system:schedule',
            statusList: [
                {
                    label: '正常',
                    value: 0
                },
                {
                    label: '暂停',
                    value: 1
                }
            ],
            addModal: false,
            addFrom: {
                id: 0,
                beanName: '',
                methodName: '',
                params: '',
                cron: '',
                status: 0,
                remark: ''
            },
            rules: {
                beanName: [
                    {required: true, message: 'Bean名称不能为空', trigger: 'blur'}
                ],
                methodName: [
                    {required: true, message: '方法名称不能为空', trigger: 'blur'}
                ],
                cron: [
                    {required: true, message: '方法名称不能为空', trigger: 'blur'}
                ]
            },
        };
    },
    methods: {
        getData () {
            this.jobColumns = jobCol.jonColumns;
            this.$get('/admin/schedule/list')
            .then( res => {
                this.jobs = res.page.rows;
                this.total = res.page.total;
                this.currentPage = res.page.pageNo;

                this.isLoading = false;
            })
            .catch(error => {
                this.isLoading = false;
                this.$Message.error(error.msg || error.message);
            });
        },
        cancelModal () {
            this.addModal = false;
        },
        handleAdd () {
            this.modalTitle = '新增定时任务';
            this.addModal = true;
        },
        handleEdit (val) {
            this.$router.push({
                name: 'manager_edit',
                params: {
                    id: val.userId
                }
            });
        },
        addModalOk () {
            this.$refs.addFrom.validate((valid) => {
                if (valid) {
                    this.saveLoading = true;
                    this.$post('/admin/schedule/saveOrUpdate', {
                        jobId: this.addFrom.id === 0 ? null : this.addFrom.id,
                        beanName: this.addFrom.beanName,
                        methodName: this.addFrom.methodName,
                        params: this.addFrom.params,
                        cron: this.addFrom.cron,
                        status: this.addFrom.status,
                        remark: this.addFrom.remark
                    }, 'json')
                    .then( res => {                   
                        this.getData();
                        this.$Message.success("操作成功");
                        this.addModal = false;                       
                    })
                    .catch(error => {
                        this.$Message.error(error.message || err.msg);
                    });
                } else {
                    // 获取表单域所有field
                    let fields = this.$refs.addFrom.fields;
                    // 聚焦错误表单域
                    try {
                         fields.forEach(element => {

                            if ('error' === element.validateState) {
                                // 这里的element无foucs()
                                let refName = element.prop;
                                this.$refs[refName].focus();
                                // 抛出异常跳出循环
                                foreach.break = new Error('StopIteration');
                            }
                         });
                    } catch (e) {
                        console.log(e);
                    }
                }
                
            });
        },
        handleDel (val, index) {
            // 删除
            let ids = val.jobId;
            this.$post('/admin/schedule/delete',
                {
                    jobIds: JSON.stringify(ids)
                }
            ).then (res => {
                this.jobs.splice(index, 1);
                this.$Message.success('删除了' + val.remark + '定时任务');
            }).catch (error => {
                console.log(error);
                this.$Message.error(error.message || error.msg);
            });
            
        },
        handleResume (val) {
            let ids = val.jobId;
            this.$post('/admin/schedule/resume',
                {
                    jobIds: JSON.stringify(ids)
                }
            ).then (res => {
                this.getData();
                this.$Message.success('已恢复定时任务');
            }).catch (error => {
                console.log(error);
                this.$Message.error(error.message || error.msg);
            });
        },
        handleStop (val) {
            let ids = val.jobId;
            this.$post('/admin/schedule/pause',
                {
                    jobIds: JSON.stringify(ids)
                }
            ).then (res => {
                this.getData();
                this.$Message.success('已暂停定时任务');
            }).catch (error => {
                console.log(error);
                this.$Message.error(error.message || error.msg);
            });
        },
        handleRun (val) {
            let ids = val.jobId;
            this.$post('/admin/schedule/run',
                {
                    jobIds: JSON.stringify(ids)
                }
            ).then (res => {
                this.getData();
                this.$Message.success('执行成功');
            }).catch (error => {
                console.log(error);
                this.$Message.error(error.message || error.msg);
            });
        },
        handleSelectAll (status) {
            this.$manager.selection.selectAll(status);
        },
        changePage () {
            console.log(this.currentPage);
            this.$get('/admin/user/list?page=' + this.currentPage)
                .then(res => {
                   
                    this.adminUsers = res.rows;
                    this.total = res.total;
                    this.currentPage = res.pageNo;
                    
                    this.isLoading = false;
                })
                .catch(error => {
                    this.isLoading = false;
                });
        }
    },
    created () {
        this.getData();
    }
};
</script>
